import { length } from '@turf/turf';
import { type LineFeature, ShapeTool } from './shape';

export class LineTool extends ShapeTool {
  addLabel = (
    id: string,
    coords: GeoJSON.Position[],
    lengths: number[] = [],
  ) => {
    const labels = lengths.map((l) => `${l.toFixed(3)} km`);
    this.createLabels(id, labels, coords);
  };

  handleCreate = (feature: GeoJSON.Feature) => {
    const line = feature as LineFeature;
    const coordinates = line.geometry.coordinates;

    const lens = [];
    const poss = [];
    // 计算每个线段的长度
    for (let i = 0; i < coordinates.length - 1; i++) {
      const segment = {
        type: 'Feature',
        geometry: {
          type: 'LineString',
          coordinates: [coordinates[i], coordinates[i + 1]],
        },
        properties: {},
      };

      const len = length(segment as LineFeature, { units: 'kilometers' });
      lens.push(len);
      poss.push([
        (coordinates[i][0] + coordinates[i + 1][0]) / 2,
        (coordinates[i][1] + coordinates[i + 1][1]) / 2,
      ]);
    }
    this.addLabel(feature.id as string, poss, lens);

    this.draw?.setDrawingMode('simple_select');
  };

  handleDelete = (feature: GeoJSON.Feature) => this.delId(feature.id as string);
}
